package ua.kiev.tosik.price.modules.clients.database.files;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IPricesFilesDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.Clients;
import ua.kiev.tosik.price.models.PricesFiles;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class PricesFilesLoadWorker extends SwingWorker<List<PricesFiles>, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.database.files");
	private List<PricesFiles> pricesFilesList;
	private Clients clients;
	private IPricesFilesDao pricesFilesDao;

	public PricesFilesLoadWorker() {
		super();
		logger.debug("Initialize PricesFilesLoadWorker");
		try {
			pricesFilesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesFilesDao();
		} catch (Exception e) {
			logger.error(e);
		}
		pricesFilesList = new ArrayList<PricesFiles>();
	}

	public void setClients(Clients clients) {
		this.clients = clients;
	}

	@Override
	protected List<PricesFiles> doInBackground() throws Exception {
		if ( clients == null || pricesFilesDao == null ) {
			throw new Exception("Can't load prices files. client NULL or Dao NULL!");
		}
		firePropertyChange("FILE_LOAD_START", null, true);
		try {
			pricesFilesList = pricesFilesDao.findByClientsId(clients.getId());
		} catch (Exception e) {
			logger.error(e);
			throw new Exception(e);
		}
		firePropertyChange("FILE_LOAD_DONE", null, true);
		return pricesFilesList;
	}

	@Override
	protected void done() {
		super.done();
		try {
			pricesFilesList = get();
			firePropertyChange("FILE_LOAD_OK", null, pricesFilesList);
		} catch (Exception e) {
			logger.error(e);
			firePropertyChange("FILE_LOAD_ERROR", null, e);
		}
	}
}
